package com.laolang.shop.modules.auth.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
@Slf4j
@Component
public class LoginValidateAuthenticationProvider implements AuthenticationProvider {

    @Qualifier("UserDetailServiceImpl")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String phone = authentication.getName();
        String pwd = (String) authentication.getCredentials();
        UserDetails userDetails = userDetailsService.loadUserByUsername(phone);
        // khl 用户不存在自动注册
        if (null == userDetails) {
            throw new UsernameNotFoundException("该手机号未注册");
        }
        // if (!passwordEncoder.matches(pwd, userDetails.getPassword())) {
        //     throw new BadCredentialsException("输入密码错误!");
        // }
        return new UsernamePasswordAuthenticationToken(userDetails, pwd, userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
